package com.yssoft.controller;

import com.alibaba.fastjson.JSONObject;
import com.yssoft.entity.core.TAccounts;
import com.yssoft.entity.core.TPersonnel;
import com.yssoft.framework.Constant;
import com.yssoft.service.core.AccountsService;

import com.yssoft.service.core.PersonService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/***
 * 登陆控制器
 */
@Controller
@ApiIgnore
public class LoginController extends BaseController{
    
    private static Logger logger=Logger.getLogger(LoginController.class);
    /***
     * 人员service
     */
    @Resource
    private AccountsService accountsService;
    @Resource
    private PersonService personService;
    /**
     * 账号登陆
     * */
    @RequestMapping(value = "login", produces = "text/html; charset=utf-8")
    public String login(HttpServletRequest request, String login_name,String password) {
        Subject sub = SecurityUtils.getSubject();
        TAccounts user =null ;
        TPersonnel personnel=null;
        String telRegex = "[1][123456789]\\d{9}";
        //设置首次加载
        if(login_name==null||"".equals(login_name) || "".equals(password)||null==password) {
        	return "login";
        }
        if(login_name!=null && login_name.matches(telRegex)){
            //当前是手机号
            personnel=personService.queryPersonByPhone(login_name);//如果使用手机号登陆，则使用手机号查询人员
        }
        if(personnel!=null){
            SecurityUtils.getSubject().getSession().setAttribute("isPhone","1");
            user = accountsService.queryAccountByPersonId(personnel.getId());//根据人员查询账号
        }else {
            SecurityUtils.getSubject().getSession().setAttribute("isPhone","0");
            user = accountsService.queryAccByLoginName(login_name);
        }
        Session session = SecurityUtils.getSubject().getSession();
        if (user == null && session.getAttribute("isLogin")!=null) {
            request.setAttribute("LOGIN_ERROR_CODE", Constant.LOGIN_ERROR_CODE_100001);
            request.setAttribute("LOGIN_ERROR_MESSAGE", Constant.LOGIN_ERROR_MESSAGE_USERERROR);
            return "login";
        } else {
            // 用户输入的账号和密码,,存到UsernamePasswordToken对象中..然后由shiro内部认证对比,
            // 认证执行者交由ShiroDbRealm中doGetAuthenticationInfo处理
            // 当以上认证成功后会向下执行,认证失败会抛出异常
            UsernamePasswordToken token = new UsernamePasswordToken(login_name,password);
            try {
                sub.login(token);
            } catch (LockedAccountException lae) {
                token.clear();
                request.setAttribute("LOGIN_ERROR_CODE", Constant.LOGIN_ERROR_CODE_100002);
                request.setAttribute("LOGIN_ERROR_MESSAGE", Constant.LOGIN_ERROR_MESSAGE_SYSTEMERROR);
                return "login";
            } catch (ExcessiveAttemptsException e) {
                token.clear();
                request.setAttribute("LOGIN_ERROR_CODE", Constant.LOGIN_ERROR_CODE_100003);
                request.setAttribute("LOGIN_ERROR_MESSAGE", "账号：" + login_name + Constant.LOGIN_ERROR_MESSAGE_MAXERROR);
                return "login";
            } catch (AuthenticationException e) {
                token.clear();
                if(session.getAttribute("isLogin")!=null) {
                	request.setAttribute("LOGIN_ERROR_CODE", Constant.LOGIN_ERROR_CODE_100001);
                    request.setAttribute("LOGIN_ERROR_MESSAGE", Constant.LOGIN_ERROR_MESSAGE_USERERROR);
                    session.removeAttribute("isLogin");
                }
               
                return "login";
            }
            return "redirect:/index";
        }
    }

    /**
     * 账号登陆接口
     * */
    @RequestMapping(value = "loginInterface" ,method = RequestMethod.POST)
    @ResponseBody
    @CrossOrigin
    public JSONObject loginInterface(String loginName, String password) {
        JSONObject jsonObject = new JSONObject();
        TAccounts user =null ;
        TPersonnel personnel=null;
        String telRegex = "[1][123456789]\\d{9}";
        if(loginName!=null && loginName.matches(telRegex)){
            //当前是手机号
            personnel=personService.queryPersonByPhone(loginName);//如果使用手机号登陆，则使用手机号查询人员
        }
        if(personnel!=null){
            SecurityUtils.getSubject().getSession().setAttribute("isPhone","1");
            user = accountsService.queryAccountByPersonId(personnel.getId());//根据人员查询账号
        }else {
            SecurityUtils.getSubject().getSession().setAttribute("isPhone","0");
            user = accountsService.queryAccByLoginName(loginName);
        }
        if (user == null  ) {
            jsonObject.put("code","1");
            jsonObject.put("msg","账号不存在");
            return jsonObject;
        } else {
              password = new SimpleHash("MD5", password , user.getSalt(), 2).toString();
            if(user.getPassword().contains(password)) {
                jsonObject.put("code", "0");
                jsonObject.put("msg", "登录成功");
                return jsonObject;
            }else{
                jsonObject.put("code","1");
                jsonObject.put("msg","密码错误");
                return jsonObject;
            }
        }
    }
    
    @RequestMapping(value = "/hrb/login")
	public String list(Model model){
		return "loginHeb";
	}
   
}
